package com.david.videoapp.hlsfunc;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.david.videoapp.R;

import java.io.File;

public class M3u8LinkGetActivity extends Activity implements HlsDownloader.OnDownLoadListener {
    private WebView mWebView;

    private TextView editText, url, downloadBtn;
    private HlsDownloader downLoader;

    private String title;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_m3u8_link_get);
        mWebView = (WebView) findViewById(R.id.webview);
        editText = findViewById(R.id.edittext);
        url = findViewById(R.id.url);

        downloadBtn = findViewById(R.id.download);

        downloadBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread() {
                    @Override
                    public void run() {
                        super.run();
                        String originUrlPath = url.getText().toString();
//                        String originUrlpath = "http://devimages.apple.com/iphone/samples/bipbop/gear1/prog_index.m3u8";
//        String originUrlpath = "http://d2zihajmogu5jn.cloudfront.net/bipbop-advanced/bipbop_16x9_variant.m3u8";
                        String preUrlPath = originUrlPath.substring(0, originUrlPath.lastIndexOf("/")+1);
                        String rootPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/downvideos";

                        String m3u8Name = originUrlPath.substring(originUrlPath.lastIndexOf("/"));
                        if (m3u8Name.contains("?")) {
                            m3u8Name = m3u8Name.substring(0, m3u8Name.indexOf("?"));
                        }
                        m3u8Name = title + ".m3u8";
                        if (new File(rootPath + "/" + m3u8Name).exists()) {
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(M3u8LinkGetActivity.this, "视频已存在", Toast.LENGTH_LONG).show();
                                }
                            });
                            return;
                        }

                        File file = new File(rootPath);
                        if (!file.exists()) {
                            file.mkdirs();
                        }
                        String fileName = "";
                        if (downLoader == null) {
                            downLoader = new HlsDownloader(originUrlPath, preUrlPath, rootPath, title);
                            downLoader.setOnDownLoadListener(M3u8LinkGetActivity.this);
                        }
                        //downLoader.setThreadQuantity(10);
                        try{
                            fileName = downLoader.download(true);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        if(fileName.isEmpty()){
                            System.out.println("下载失败");
                        }else{
                            System.err.println("下载成功");
                        }
                    }
                }.start();
            }
        });

        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);

        mWebView.setWebChromeClient(new WebChromeClient() {
        });

        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                title = view.getTitle();
            }

            @Override
                                      public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                                          return super.shouldOverrideUrlLoading(view, request);
                                      }

                                      @Nullable
                                      @Override
                                      public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
                                          if (request.getUrl().toString().contains(".m3u8")) {
                                              downloadBtn.post(new Runnable() {
                                                  @Override
                                                  public void run() {
                                                      url.setText(request.getUrl().toString());
                                                      downloadBtn.setVisibility(View.VISIBLE);
                                                  }
                                              });
                                          }
                                          return super.shouldInterceptRequest(view, request);
                                      }
                                  }
        );
        findViewById(R.id.search).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (editText.getText().length() > 0) {
                    mWebView.loadUrl(editText.getText().toString());
                }
            }
        });
    }

    @Override
    public void start(int allSize) {
        Message message = handler.obtainMessage();
        message.what = 1;
        message.arg2 = allSize;
        handler.sendMessage(message);
    }

    @Override
    public void onDownLoading(int allSize, int downSize) {
        Message message = handler.obtainMessage();
        message.what = 0;
        message.arg1 = downSize;
        message.arg2 = allSize;
        handler.sendMessage(message);
    }

    @Override
    public void onFinish(int allSize) {
        Message message = handler.obtainMessage();
        message.what = 2;
        handler.sendMessage(message);
    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    downloadBtn.setText("下载："+msg.arg1+"/" + msg.arg2);
                    break;
                case 1:
                    downloadBtn.setText("下载：0/" + msg.arg2);
                    break;
                case 2:
                    downloadBtn.setText("下载");
                    break;
            }
        }
    };
}
